package com.javalearn;

import java.util.LinkedList;
import java.util.List;

public class SimpleThreadPool {
	private static final int DEFAULT_WORKER_NUMS = 5;
	
	private List<Job> jobList = new LinkedList<Job>();
	private List<Worker> workerList = new LinkedList<Worker>();
	
	public SimpleThreadPool() {
		initWorkers(DEFAULT_WORKER_NUMS);
	}
	public void shutdown() {
		for(Worker worker : workerList) {
			worker.shutdown();
		}
	}
	public static class Job implements Runnable{
		private String jobName;
		private String getName() {
			return jobName;
		}
		public Job(String jobName) {
			this.jobName = jobName;
		}
		public void run() {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public class Worker implements Runnable{
		private volatile boolean running = true;
		public void run() {
			while(running) {
				Job job = null;
				synchronized(jobList) {
					while(jobList.isEmpty()) {
						try {
							jobList.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					job = jobList.remove(0);
				}
				if(job!=null) {
					String threadName = Thread.currentThread().getName();
					System.out.println(threadName+" is executing job: "+job.getName());
					job.run();
				}
			}
		}
		public void shutdown() {
			running = false;
		}
	}
	
	
	public void execute(Job job) {
		synchronized(jobList) {
			jobList.add(job);
			jobList.notify();
		}
	}
	private void initWorkers(int num) {
		for(int i=0;i<num;i++) {
			Worker worker = new Worker();
			workerList.add(worker);
			Thread thread = new Thread(worker,"worker-"+i);
			thread.start();
		}
	}
	
	public static void main(String[] args) {
		SimpleThreadPool stp = new SimpleThreadPool();
		for(int i=0;i<10;i++) {
			Job job = new Job(String.valueOf(i));
			stp.execute(job);
		}		
	}
}
